package com.shiroha.notification.service.impl;

import com.shiroha.common.bean.RedisConstant;
import com.shiroha.common.exception.InternalServiceException;
import com.shiroha.common.utils.RedisUtils;
import com.shiroha.notification.config.EmailApiClient;
import com.shiroha.notification.service.IEmailService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@AllArgsConstructor
@Slf4j
public class EmailServiceImpl implements IEmailService {

    private final RedisUtils redisUtils;
    private final EmailApiClient emailApiClient;


    /**
     * 发送邮件验证码到指定邮箱
     *
     * @param email 邮箱
     */
    @Override
    public void sendEmailCode(String email) {
        String code = generateCode();
        // 存储验证码到Redis中，并设置过期时间为5分钟
        redisUtils.setCacheObject(RedisConstant.CODE_KEY_PREFIX + email, code, 5 * 60, TimeUnit.SECONDS);
        try {
            emailApiClient.sendEmail(email, code);
        }catch (Exception e){
            throw new InternalServiceException(e.getMessage());
        }
    }

    /**
     * 检验邮箱验证码
     *
     * @param email 邮箱
     * @param code  验证码
     */
    @Override
    public Boolean checkCode(String email, String code) {
        return code.equals(redisUtils.getCacheObject(RedisConstant.CODE_KEY_PREFIX + email));
    }

    private String generateCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }
}